import React, { useState } from 'react';
import {
  Grid,
  CssBaseline,
  ThemeProvider,
  Box,
  useMediaQuery,
  GlobalStyles,
  CircularProgress
} from '@mui/material';
import getTheme from 'themes/Theme';
import DashboardDrawerProtected from 'components/organisms/DashboardDrawerProtected';
import DashboardDrawer from 'components/organisms/DashboardDrawer';
import MobileDrawer from 'components/organisms/MobileDrawer';
import { SnackBar } from 'components/elements/SnackBar';
import Footer from 'components/organisms/Footer';
import { useAuth } from "contexts/AuthContext";
import { useDarkMode } from 'contexts/DarkMode';
import { useDashboardDrawerProtected } from 'contexts/DashboardDrawerProtectedContext';
import { useDashboardDrawer } from 'contexts/DashboardDrawerContext';
import { useDrawer } from 'contexts/DrawerContext';
import { useMenu } from 'contexts/MenuContext';
import { useLocation, Navigate } from 'react-router-dom';
import getNewTheme from 'themes/NewTheme';
import TopIconsPrivate from 'components/organisms/TopIconsPrivate';
import DrawerComponent from 'components/organisms/DrawerComponent';
import { AppBarProvider } from 'contexts/AppBarContext';
import ReusableToolbar from 'components/organisms/ReusableToolbar';
import AdaptiveLayout from 'components/elements/AdaptiveLayout';

// Loading component
const LoadingComponent = () => (
  <Box 
    sx={{ 
      display: 'flex', 
      justifyContent: 'center', 
      alignItems: 'center', 
      height: '100vh' 
    }}
  >
    <CircularProgress />
  </Box>
);

const PrivateLayout = ({ children }) => {
  const { darkMode } = useDarkMode();
  const { dashboardDrawerProtectedOpen, toggleDashboardDrawerProtected } = useDashboardDrawerProtected();
  const { dashboardDrawerOpen, toggleDashboardDrawer } = useDashboardDrawer();
  const { drawerOpen, toggleDrawer } = useDrawer();
  const { isMenuOpen, toggleMenu } = useMenu();
  const isXs = useMediaQuery('(max-width:600px)');
  const location = useLocation();
  const isHomePage = location.pathname === '/';
  const [useTheme] = useState(false);
  
  // Safe access to auth context with isLoading check
  const { user, isLoading } = useAuth();
  
  // Show loading component while auth state is being determined
  if (isLoading) {
    return <LoadingComponent />;
  }
  
  // Redirect to login if no user
  if (!user) {
    return <Navigate to="/auth/login" replace />;
  }

  const theme = useTheme
    ? isHomePage
      ? getNewTheme(darkMode)
      : getNewTheme(darkMode, isXs)
    : isHomePage
      ? getTheme(darkMode)
      : getTheme(darkMode, isXs);

  return (
    <AppBarProvider>
      <ThemeProvider theme={theme}>
        <SnackBar>
          <CssBaseline />
          <GlobalStyles 
            styles={{
              'html, body': {
                minHeight: '100vh',
                margin: 0,
                padding: 0,
              },
              body: {
                background: useTheme
                  ? isHomePage
                    ? darkMode 
                      ? 'rgba(13, 14, 14, 1)'
                      : 'linear-gradient(135deg, rgba(0, 2, 3, 0.9) 0%, rgba(33, 33, 33, 0.9) 100%)'
                    : darkMode
                      ? '#000000'
                      : '#ffffff'
                  : isHomePage
                    ? darkMode
                      ? '#000000'
                      : '#ffffff !important'
                    : darkMode
                      ? '#000000'
                      : '#ffffff !important',
              },
            }}
          />
      
          <DrawerComponent 
            successCode="0000"
            buttonBackgroundColor="rgba(97, 218, 251, .2)"
            buttonHoverColor="rgba(97, 218, 251, .6)"
            buttonActiveColor="rgba(97, 218, 251, .6)"
            enableVibration={true}
            darkMode={darkMode}
          />
      
          {/* Wrapper Box with height 100% */}
          <Box sx={{ height: '100vh', overflowY: 'auto' }}>
            {/* Only render these components when user is available */}
            {user && (
              <>
                <TopIconsPrivate
                  isXs={isXs} 
                  isHomePage={isHomePage} 
                  useTheme={useTheme}
                  user={user}
                  toggleDashboardDrawer={toggleDashboardDrawer}
                  toggleDashboardDrawerProtected={toggleDashboardDrawerProtected}
                  isMenuOpen={isMenuOpen}
                  toggleMenu={toggleMenu}
                  darkMode={darkMode}
                />
                
                <ReusableToolbar
                  darkMode={darkMode}
                  user={user}
                  toggleDashboardDrawerProtected={toggleDashboardDrawerProtected}
                  sx={{
                    padding: 0,
                    minHeight: 'auto'
                  }}
                />
              </>
            )}
            
            <Grid 
              container 
              columns={12}
            >
              <Grid item xs={12} sx={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
                {!isXs ? (
                  <AdaptiveLayout
                    backgroundColor={null}
                    marginY={0}
                    paddingY={0}
                    paddingX={0}
                    centered={true}
                    fullWidth={true}
                    useInnerWrapper={true}
                  >
                    <DashboardDrawerProtected
                      anchor="left"
                      open={dashboardDrawerProtectedOpen}
                      toggleDashboardDrawerProtected={toggleDashboardDrawerProtected}
                      darkMode={darkMode}
                    />
                    <DashboardDrawer
                      anchor="left"
                      open={dashboardDrawerOpen}
                      toggleDashboardDrawer={toggleDashboardDrawer}
                      darkMode={darkMode}
                    />
                    <MobileDrawer
                      anchor="left"
                      open={drawerOpen}
                      toggleDrawer={toggleDrawer}
                      darkMode={darkMode}
                    />
                  </AdaptiveLayout>
                ) : (
                  <>
                    <DashboardDrawerProtected
                      anchor="left"
                      open={dashboardDrawerProtectedOpen}
                      toggleDashboardDrawerProtected={toggleDashboardDrawerProtected}
                      darkMode={darkMode}
                    />
                    <DashboardDrawer
                      anchor="left"
                      open={dashboardDrawerOpen}
                      toggleDashboardDrawer={toggleDashboardDrawer}
                      darkMode={darkMode}
                    />
                    <MobileDrawer
                      anchor="left"
                      open={drawerOpen}
                      toggleDrawer={toggleDrawer}
                      darkMode={darkMode}
                    />
                  </>
                )}
              </Grid>
              
              <Grid item xs={12} sx={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
                <AdaptiveLayout
                  backgroundColor={null}
                  marginY={0}
                  paddingY={0}
                  paddingX={0}
                  centered={true}
                  fullWidth={true}
                  useInnerWrapper={true}
                >
                  {children}
                </AdaptiveLayout>
              </Grid>
              
              <Grid item xs={12} sx={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
                <AdaptiveLayout
                  backgroundColor={null}
                  marginY={0}
                  paddingY={0}
                  paddingX={0}
                  centered={true}
                  fullWidth={true}
                  useInnerWrapper={true}
                >
                  <Footer darkMode={darkMode} />
                </AdaptiveLayout>
              </Grid>
            </Grid>
          </Box>
        </SnackBar>
      </ThemeProvider>
    </AppBarProvider>
  );
};

export default PrivateLayout;